package servlet.zyb;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class LoginServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req, resp);
	}

	public void process(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		List<String> list = new ArrayList<String>();
		String username = req.getParameter("username");
		String password = req.getParameter("password");

		SAXBuilder read = new SAXBuilder();
		Document document = null;
		try {
			document = read.build(new File(
					"E:\\MyeclipseWorkspace\\vote\\user.xml"));
		} catch (JDOMException e) {

			e.printStackTrace();
		}
		Element root = document.getRootElement();
		System.out.println(root.getName());

		Element user = root.getChild("user");

		Element xmlUsername = user.getChild("username");
		String name = xmlUsername.getText();
		System.out.println(name);

		Element xmlPassword = user.getChild("password");

		String pass = xmlPassword.getText();

		System.out.println(pass);
		if (username == "" || password == "") {

			list.add("账号和密码为空,登陆失败");
			req.setAttribute("error", list);
			req.getRequestDispatcher("loginerror.jsp").forward(req, resp);
		} else if (!username.equals(name) || !pass.equals(password)) {

			list.add("账号密码错误，登陆失败");
			req.setAttribute("error", list);
			req.getRequestDispatcher("loginerror.jsp").forward(req, resp);
		} else if (username.equals(name) && password.equals(pass)) {
			req.getSession().setAttribute("username", username);
			req.getRequestDispatcher("loginsuccess.jsp").forward(req, resp);

		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		process(req, resp);
	}
}
